package com.easysoft.commons.interceptor;

import com.easysoft.commons.utils.UUIDUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class CSRFInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = null;
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("csrf_token")) {
                token = cookie.getValue();
            }
        }
        if (request.getMethod().equalsIgnoreCase("POST")) {
            String requestType = request.getHeader("X-Requested-With");
            //AJAX POST 请求
            if (requestType != null && requestType.equalsIgnoreCase("XMLHttpRequest")) {
                if (token != null && token.equals(request.getHeader("csrf_token")))
                    return true;
            } else if (token != null && token.equals(request.getParameter("csrf_token"))) {//普通表单POST方法
                return true;
            }

            //SC_FORBIDDEN，状态码是403，表示服务器明白客户的请求，但拒绝响应
            response.sendError(403, "Bad or missing token!");
            return false;
        }

        if (token==null){
            token = UUIDUtils.get36UUID();
            Cookie cookie = new Cookie("csrf_token",token);
            response.addCookie(cookie);
        }

        request.setAttribute("token", token);
        return true;
    }
}
